package com.suns.commom;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * 自定义获取上下文帮助类 从applicationContext中获取 spring的bean
 * 并且在spring-servlet.xml中进行配置
 */
//加入注解使其被spring管理
@Component("applicationContextHelper")
public class ApplicationContextHelper implements ApplicationContextAware{

    //定义全局ApplicationContext
    private static ApplicationContext applicationContext;
    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        applicationContext = context;
    }

    //从applicationContext中获取 spring的bean
    public static <T> T popBean(Class<T> clazz) {
        if (applicationContext == null) {
            return null;
        }
        return applicationContext.getBean(clazz);
    }

    public static <T> T popBean(String name, Class<T> clazz) {
        if (applicationContext == null) {
            return null;
        }

        return applicationContext.getBean(name,clazz);
    }
}
